package com.dddframework.web.auth.interceptor;

import com.dddframework.core.context.ThreadContext;
import com.dddframework.core.contract.exception.ServiceException;
import com.dddframework.web.auth.annotation.Inside;
import com.dddframework.web.core.AccessToken;
import com.dddframework.web.interceptor.BaseWebInterceptor;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import static com.dddframework.core.contract.constant.ContextConstants.ACCESS_TOKEN;
import static com.dddframework.core.contract.enums.ResultCode.NO_ACCESS_TOKEN;

/**
 * 开放接口拦截器
 * 校验Header的access-token信息，access-token在AuthController获取
 */
public class OpenApiWebInterceptor extends BaseWebInterceptor {
    @Override
    public String[] pathPatterns() {
        return new String[]{"/openapi/**", "/open/**"};
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (handler.getClass() == ResourceHttpRequestHandler.class) return Boolean.TRUE;
        HandlerMethod method = (HandlerMethod) handler;
        //判断访问的Controller或方法是否添加@Inside注解
        Inside insideType = method.getMethod().getDeclaringClass().getDeclaredAnnotation(Inside.class);
        Inside insideMethod = method.getMethodAnnotation(Inside.class);
        if (insideType != null || insideMethod != null) {
            return Boolean.TRUE;
        }
        // AccessToken校验
        if (!ThreadContext.contains(ACCESS_TOKEN)) {
            throw new ServiceException(NO_ACCESS_TOKEN);
        }
        // AccessToken续期
        AccessToken.expire();
        return Boolean.TRUE;
    }

    @Override
    public int getOrder() {
        return -198;
    }
}